<?php
namespace app\client\controller;

use app\common\lib\Redis;

class LuckDraw extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    
    public function viewList() {
        $params = request()->get();
        $pk = isset($params['lastPk']) ? intval($params['lastPk']) : 0;
        $pageSize = isset($params['pageSize']) ? intval($params['pageSize']) : 20;
        $where = [['user_id', '=', $this->userid]];
        
        if($pk > 0) {
            $where[] = ['id', '<', $pk];
        }
        
        $chatList = [];
        
        $rows = model('ChatLuckDraw')->where($where)->order('id desc')->field(['id', 'chat_id', 'number', 'total', 'end_time', 'join_number', 'prize_number', 'status'])->limit($pageSize)->select()->toArray();
        if(!empty($rows)) {
            $chatIds = [];
            foreach ($rows as $row) {
                array_push($chatIds, $row['chat_id']);
            }
            
            $chatList = model('Chat')->alias('a')->join('__CHAT_GOODS__ b', 'a.chat_id=b.chat_id')->where(['a.chat_id' => $chatIds])->field(['a.cover', 'a.chat_id', 'b.goods_name'])->select()->toArray();
            if(!empty($chatList)) {
                foreach ($chatList as $k => $chat) {
                    foreach ($rows as $row) {
                        if($chat['chat_id'] == $row['chat_id']) {
                            $chatList[$k] = array_merge($chat, $row);
                        }
                    }
                }
            }
        }
        return successResult(['list' => $chatList]);
    }
    
    public function drawList() {
        if($this->noLogin()) {
            return successResult(['list' => []]);
        }
        $hadIds = model('LuckDrawLog')->values(['user_id' => $this->userid], 'chat_id');
        $time = time();
        
        
        $where = [
            ['status', '=', 0],
            ['start_time', '<=', $time],
            ['end_time', '>=', $time]
        ];
        
        if($hadIds) {
            $where[] = ['chat_id', 'not in', $hadIds];
        }
        
        $chatList = [];
        $draws = model('ChatLuckDraw')->where($where)->limit(10)->field(['chat_id'])->select();
        if($draws) {
            $chatIds = [];
            foreach ($draws as $item) {
                array_push($chatIds, $item['chat_id']);
            }
            
            if($chatIds) {
                $chatList = model('Chat')->findAll(['chat_id' => $chatIds], ['user_id', 'chat_id']);
                $userIds = [];
                foreach ($chatList as $chat) {
                    array_push($userIds, $chat['user_id']);
                }
                
                if(!empty($userIds)) {
                    $userList = model('User')->findAll(['user_id' => $userIds], ['user_id', 'nickname', 'avatar']);
                    
                    foreach ($chatList as $k => $chat) {
                        foreach ($userList as $user) {
                            if($chat['user_id'] == $user['user_id']) {
                                $chatList[$k]['user'] = $user;
                            }
                        }
                    }
                }
                
            }
        }
        
        return successResult(['list' => $chatList]);
    }
    
    //抽奖
    public function grab() {
        $chatId = request()->post('id', 0, 'intval');
        if($chatId <= 0){
            return errorResult('a');
        }
        
        $userId = $this->userid;

        $logModel = model('LuckDrawLog');
        $receiveLog = $logModel->findOne(['user_id' => $userId, 'chat_id' => $chatId], ['result']);
        if(!empty($receiveLog)){
            return successResult(['result' => $receiveLog['result']]);
        }
        
        $time = time();
        
        $model = model('ChatLuckDraw');
        
        $model->startTrans();
        
        try {
            
            $luck = $model->where(['chat_id' => $chatId])->field(['join_number', 'prize_number', 'start_time', 'end_time', 'id'])->lock(true)->find();
            if(empty($luck)) {
                $model->rollback();
                return errorResult();
            }
            
            if($luck['start_time'] > $time) {
                $model->rollback();
                return errorResult('抽奖活动还没开始~');
            }
            
            if($luck['end_time'] <= $time) {
                $model->rollback();
                return errorResult('抽奖活动结束了~');
            }
            
            $redis = new Redis();
            $result = $redis->handler()->lPop('chat_luck_draw_' . $chatId); //抢到的红包金额
            if($result === false) {
                $model->rollback();
                $redis->close();
                return errorResult('抽奖已经完啦~');
            }
            
            $updateData = ['join_number' => $luck['join_number'] + 1];
            
            $len = $redis->handler()->lLen('chat_luck_draw_' . $chatId);
            if($len <= 0) {
                $updateData['status'] = 1;
            }
            if($result == 1) {
                $updateData['prize_number'] = $luck['prize_number'] + 1;
            }
            
            $model->modify(['id' => $luck['id']], $updateData);
            $logModel->add(['chat_id' => $chatId, 'user_id' => $this->userid, 'result' => $result, 'add_time' => $time]);
            
            $model->commit();
            
            return successResult(['result' => $result]);
        } catch (\Exception $e) {
            $model->rollback();
            return errorResult();
        }
        

        
        
    }
    
    
    public function draw() {
        $params = request()->get();
        $chatId = isset($params['id']) ? intval($params['id']) : 0;
        $result = isset($params['result']) ? intval($params['result']) : 0;
        if($chatId <= 0){
            return errorResult('a');
        }
        
        $redis = new Redis();
        $chat = $redis->get(redisChatKey($chatId));
        $chat = json_decode($chat, true);
        $chat['user'] = $redis->get(redisUserKey($chat['user_id']));
        $redis->close();
        
        $rep = ['chat' => $chat];
        
        if($result != 2) {
            $log = model('LuckDrawLog')->findOne(['user_id' => $this->userid, 'chat_id' => $chatId], ['result', 'order']);
            $rep['result'] = $log['result'];
            $rep['order'] = $log['order'];
        }
        
        return successResult($rep);
        
    }
    
    public function drawView (){
        $id = request()->get('id', 0, 'intval');
        if($id <= 0){
            return errorResult();
        }

        $userList = [];
        $quantity = 0;
        
        $model = model('LuckDrawLog');
        
        $list = $model->where(['chat_id' => $id])->field('user_id')->limit(10)->select()->toArray();
        if(!empty($list)) {
            $userIds = [];
            foreach ($list as $v) {
                array_push($userIds, $v['user_id']);
            }
            
            $userList = model('User')->findAll(['user_id' => $userIds], ['avatar']);
            
            $quantity = count($list);
            if($quantity < 10) {
                $quantity = $model->where(['chat_id' => $id])->count();
            }
            
            
        }

        return successResult(['quantity' => $quantity, 'list' => $userList]);
    }
    
    public function order() {
        $params = request()->post();
        $chatId = isset($params['id']) ? intval($params['id']) : 0;
        $addressId = isset($params['address']) ? intval($params['address']) : 0;
        if($chatId <= 0 || $addressId <= 0) {
            return errorResult();
        }
        
        $remark = isset($params['remark']) ? trim($params['remark']) : '';
        
        $userId = $this->userid;
        
        $logModel = model('LuckDrawLog');
        
        $log = $logModel->findOne(['chat_id' => $chatId, 'user_id' => $userId], ['result', 'order', 'id']);
        if(empty($log) || $log['result'] == 0 || $log['order'] == 1) {
            return errorResult();
        }
        
        $address = model('DeliveryAddress')->findOne(['id' => $addressId]);
        if(empty($address) || $address['user_id'] != $userId) {
            return errorResult();
        }
        
        $goods = model('ChatGoods')->findOne(['chat_id' => $chatId], ['sale_price', 'goods_name', 'goods_no']);
        if(empty($goods)) {
            return errorResult();
        }
        
        $chat = model('Chat')->findOne(['chat_id' => $chatId], ['user_id', 'cover']);
        
        $orderData = [
            'user_id' => $userId,
            'order_no' => getOrderNo($userId),
            'order_type' => 3,
            'status' => 2,
            'pay_status' => 1,
            'store_id' => $chat['user_id'],
            'quantity' => 1,
            'amount' => $goods['sale_price'],
            'consignee' => $address['consignee'],
            'mobile' => $address['mobile'],
            'province' => $address['province'],
            'city' => $address['city'],
            'district' => $address['district'],
            'address' => $address['address'],
            'remarks' => $remark,
            'create_time' => time()
        ];
        
        $model = model('Order');
        
        $model->startTrans();
        
        try {
            
            $rs = $logModel->modify(['id' => $log['id']], ['order' => 1]);
            if(!$rs) {
                $model->rollback();
                return errorResult();
            }
            
            $orderId = $model->add($orderData);
            if(!$orderId) {
                $model->rollback();
                return errorResult();
            }
            
            $rs = model('OrderGoods')->add(['order_id' => $orderId, 'chat_id' => $chatId, 'cover' => $chat['cover'], 'goods_name' => $goods['goods_name'], 'goods_no' => $goods['goods_no'], 'price' => $goods['sale_price'], 'quantity' => 1]);
            if(!$rs) {
                $model->rollback();
                return errorResult();
            }
            
            $model->commit();
            return successResult(['order_id' => $orderId]);
        } catch (\Exception $e) {
            $model->rollback();
            return errorResult($e->getMessage());
        }
        
        
        
    }
}
























